import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { PluginLocal, PluginLocalTool } from '@shared/types/entity'
import { InputSchemaData } from '@shared/types/ai'
export type PluginLocalItem = PluginLocal & {
  tools: PluginLocalTool[]
}

export const defaultItem: InputSchemaData = {
  name: '',
  type: 'string',
  defaultValue: '',
  description: '',
  required: true,
  location: 'query',
  visible: true,
  items: []
}

// 根据数组递归,找到最后那个对象
export function recursive(data: InputSchemaData[], indexs: number[]): InputSchemaData[] {
  let current: InputSchemaData[] = data
  for (let i = 0; i < indexs.length; i++) {
    const idx = indexs[i]
    current = current[idx]?.items || []
  }
  return current
}

interface InputToolSchemaStore {
  data: InputSchemaData[]
  getData: () => InputSchemaData[]
  add: (indexs: number[]) => void
  remove: (indexs: number[]) => void
  update: (indexs: number[], updates: Partial<InputSchemaData>) => void
  init: (data: InputSchemaData[]) => void
}
const useInputToolSchemaStore = create<InputToolSchemaStore>()(
  immer(
    (set, get): InputToolSchemaStore => ({
      data: [],
      getData: () => get().data,
      add: (indexs) =>
        set((state) => {
          const items = recursive(state.data, indexs)
          items.push(defaultItem)
        }),
      remove: (indexs) =>
        set((state) => {
          if (indexs.length > 0) {
            const index = indexs.pop()
            recursive(state.data, indexs).splice(index!, 1)
          }
        }),
      update: (indexs, updates) =>
        set((state) => {
          console.log('update1', indexs)
          console.log('update2', updates)
          if (indexs.length > 0) {
            const index = indexs.pop()
            const item = recursive(state.data, indexs)[index!]
            Object.assign(item, updates)
          }
        }),
      init: (data: InputSchemaData[]) =>
        set((state) => {
          state.data = data
        })
    })
  )
)

export default useInputToolSchemaStore
